<template>
  <div class="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100  ">
    <div class="max-w-4xl mx-auto px-4 py-8">
      <!-- Header -->
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900  mb-3">
          Launch Your <span class="bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">24/7 AI Team</span>
        </h1>
        <p class="text-gray-600  max-w-2xl mx-auto">
          Spend pennies to build a team that works around the clock, turning your ideas into reality without any intervention from you.
        </p>
      </div>

      <!-- Main Content -->
      <div class="space-y-6">
        <!-- Basic Information Section -->
        <form @submit.prevent="handleSubmit">
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <div class="flex items-center space-x-3 mb-4">
              <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
              </div>
              <h2 class="text-lg font-semibold text-gray-900 ">Team Information</h2>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div>
                <label class="block text-xs font-medium text-gray-700  mb-1">Team Name</label>
                <input 
                  v-model="form.name"
                  type="text" 
                  required
                  class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200"
                  placeholder="Enter your team name"
                />
              </div>

              <div>
                <label class="block text-xs font-medium text-gray-700  mb-1">Project Type</label>
                <div class="relative">
                  <button
                    type="button"
                    @click.prevent="toggleProjectTypeDropdown"
                    class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 flex items-center justify-between"
                  >
                    <span>{{ getProjectTypeLabel(form.projectType) || 'Select project type' }}</span>
                    <svg class="w-3 h-3 text-gray-400  transition-transform duration-200" :class="{ 'rotate-180': showProjectTypeDropdown }" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  
                  <!-- Dropdown Options -->
                  <div 
                    v-if="showProjectTypeDropdown"
                    class="absolute z-10 w-full mt-1 bg-white  border border-gray-300  rounded-md shadow-lg max-h-60 overflow-auto"
                  >
                    <button
                      v-for="option in projectTypeOptions"
                      :key="option.value"
                      type="button"
                      @click="selectProjectType(option.value)"
                      class="w-full px-3 py-2 text-sm text-left text-gray-900  hover:bg-gray-100  transition-colors duration-200"
                    >
                      {{ option.label }}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- Custom Project Type Input -->
            <div v-if="form.projectType === 'other'" class="mt-3">
              <label class="block text-xs font-medium text-gray-700  mb-1">Custom Project Type</label>
              <input 
                v-model="form.customProjectType"
                type="text" 
                class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200"
                placeholder="Enter your custom project type"
              />
            </div>

            <div class="mt-3">
              <label class="block text-xs font-medium text-gray-700  mb-1">Project Description</label>
              <textarea 
                v-model="form.description"
                required
                rows="2"
                class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 resize-none"
                placeholder="Describe what this team will accomplish"
              ></textarea>
            </div>

            <div class="mt-3">
              <label class="block text-xs font-medium text-gray-700  mb-1">Project Requirements</label>
              <textarea 
                v-model="form.projectRequirements"
                required
                rows="3"
                class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 resize-none"
                placeholder="Describe the specific project or task this team will handle"
              ></textarea>
            </div>
          </div>
        </form>

        <!-- Agent Selection Section -->
        <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center space-x-3">
              <div class="w-8 h-8 bg-gradient-to-br from-green-500 to-blue-600 rounded-lg flex items-center justify-center">
                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <h2 class="text-lg font-semibold text-gray-900 ">Select AI Agents</h2>
            </div>
            <button
              type="button"
              @click.prevent="getRecommendedAgents"
              class="px-3 py-1.5 text-xs bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-md hover:from-purple-600 hover:to-pink-600 transition-all duration-200"
            >
              Get Recommendations
            </button>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
            <div 
              v-for="agent in availableAgents" 
              :key="agent.id"
              @click="navigateToAgent(agent.id)"
              class="group relative bg-white  rounded-lg border border-gray-200  hover:border-blue-300  transition-all duration-300 hover:shadow-md overflow-hidden cursor-pointer"
            >
              <!-- Selection Checkbox -->
              <div class="absolute top-2 right-2 z-10">
                <input 
                  :checked="form.selectedAgents.includes(agent.id)"
                  type="checkbox" 
                  class="w-3 h-3 text-blue-600 bg-white border-gray-300 rounded focus:ring-0 focus:outline-none   shadow-sm"
                  @change.stop="toggleAgentSelection(agent.id)"
                />
              </div>

              <!-- Category Tag -->
              <div class="absolute top-2 left-2 z-10">
                <span class="px-2 py-1 bg-blue-100 text-blue-800   rounded-md text-xs font-medium">
                  {{ formatCategory(agent.category) }}
                </span>
              </div>

              <!-- Agent Image/Logo -->
              <div class="bg-gradient-to-br from-blue-50 to-purple-50   h-20 flex items-center justify-center relative">
                <div class="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center text-white text-lg font-bold shadow-md relative">
                  {{ agent.metadata.logo }}
                  <!-- Online Status Badge -->
                  <div class="absolute -bottom-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-white "></div>
                </div>
              </div>

              <!-- Agent Content -->
              <div class="p-3">
                <!-- Title and Role -->
                <div class="mb-2">
                  <h3 class="font-semibold text-gray-900  text-sm line-clamp-1 group-hover:text-blue-600  transition-colors">
                    {{ agent.name }}
                  </h3>
                </div>

                <!-- Rating and Usage -->
                <div class="flex items-center justify-between mb-2">
                  <div class="flex items-center space-x-1">
                    <div class="flex items-center">
                      <span class="text-yellow-400 text-xs">⭐</span>
                      <span class="text-xs text-gray-600  font-medium ml-1">{{ agent.metadata.rating }}</span>
                    </div>
                    <span class="text-xs text-gray-400">•</span>
                    <span class="text-xs text-gray-500 ">{{ (agent.metadata as any).usage || '1.2k' }} users</span>
                  </div>
                </div>

                <!-- Description -->
                <p class="text-xs text-gray-600  line-clamp-2 mb-3 leading-relaxed">
                  {{ agent.description }}
                </p>

                <!-- Skills Tags -->
                <div class="flex flex-wrap gap-1 mb-3">
                  <span class="px-2 py-1 bg-blue-50 text-blue-700 /30  rounded text-xs">
                    {{ (agent.metadata as any).skill1 || 'Process Optimization' }}
                  </span>
                  <span class="px-2 py-1 bg-blue-50 text-blue-700 /30  rounded text-xs">
                    {{ (agent.metadata as any).skill2 || 'Workflow Design' }}
                  </span>
                  <span v-if="(agent.metadata as any).skill3" class="px-2 py-1 bg-purple-100 text-purple-700   rounded text-xs">
                    +1
                  </span>
                </div>

                <!-- Pricing and Action -->
                <div class="flex items-center justify-between">
                  <div class="flex flex-col">
                    <span class="text-sm font-bold text-gray-900 ">
                      ${{ agent.pricing.price || '150' }}
                    </span>
                    <span class="text-xs text-gray-500 ">
                      {{ (agent.pricing as any).unit || 'Per Hour' }}
                    </span>
                  </div>
                  <button 
                    class="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white text-xs font-medium rounded-md transition-colors duration-200"
                    @click.stop="toggleAgentSelection(agent.id)"
                  >
                    {{ form.selectedAgents.includes(agent.id) ? 'Selected' : 'Use' }}
                  </button>
                </div>
              </div>

              <!-- Hover Overlay -->
              <div class="absolute inset-0 bg-gradient-to-t from-blue-500/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"></div>
            </div>
          </div>
        </div>

        <!-- AI Service Configuration Section -->
        <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
          <div class="flex items-center space-x-3 mb-4">
            <div class="w-8 h-8 bg-gradient-to-br from-orange-500 to-red-600 rounded-lg flex items-center justify-center">
              <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
            </div>
            <h2 class="text-lg font-semibold text-gray-900 ">AI Service Configuration</h2>
          </div>

          <!-- Service Type Selection -->
          <div class="space-y-3">
            <div class="flex items-center space-x-4">
              <label class="flex items-center">
                <input 
                  v-model="form.apiConfig.type"
                  type="radio" 
                  value="official"
                  class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500   focus:ring-2   focus:ring-0 focus:outline-none"
                />
                <span class="ml-2 text-sm text-gray-700 ">Official Service</span>
              </label>
              <label class="flex items-center">
                <input 
                  v-model="form.apiConfig.type"
                  type="radio" 
                  value="custom"
                  class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500   focus:ring-2   focus:ring-0 focus:outline-none"
                />
                <span class="ml-2 text-sm text-gray-700 ">Custom Service</span>
              </label>
            </div>

            <!-- Custom Service Configuration -->
            <div v-if="form.apiConfig.type === 'custom'" class="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div>
                <label class="block text-xs font-medium text-gray-700  mb-1">Service URL</label>
                <input 
                  v-model="form.apiConfig.baseUrl"
                  type="url" 
                  class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200"
                  placeholder="https://api.example.com"
                />
              </div>

              <div>
                <label class="block text-xs font-medium text-gray-700  mb-1">API Key</label>
                <input 
                  v-model="form.apiConfig.apiKey"
                  type="password" 
                  class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200"
                  placeholder="Enter your API key"
                />
              </div>

              <div>
                <label class="block text-xs font-medium text-gray-700  mb-1">Model Name</label>
                <input 
                  v-model="form.apiConfig.modelName"
                  type="text" 
                  class="w-full px-3 py-2 text-sm border border-gray-300  rounded-md bg-white  text-gray-900  focus:outline-none focus:ring-1 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200"
                  placeholder="e.g., gpt-4, claude-3-sonnet"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- Action Button -->
        <div class="flex justify-center pt-6">
          <button 
            type="button"
            @click="handleSubmit"
            :disabled="isSubmitting || form.selectedAgents.length === 0"
            class="px-8 py-3 text-sm font-semibold text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105"
          >
            {{ isSubmitting ? 'Launching Team...' : 'Launch Your 24/7 Team' }}
          </button>
        </div>
      </div>
    </div>

    <!-- Toast Notification -->
    <div 
      v-if="showToast"
      class="fixed top-4 right-4 z-50 max-w-sm w-full bg-white  rounded-lg shadow-lg border border-gray-200  p-4 transform transition-all duration-300 ease-in-out"
      :class="{
        'translate-x-0 opacity-100': showToast,
        'translate-x-full opacity-0': !showToast
      }"
    >
      <div class="flex items-start space-x-3">
        <div 
          class="flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center"
          :class="{
            'bg-green-100 text-green-600  ': toastType === 'success',
            'bg-red-100 text-red-600  ': toastType === 'error',
            'bg-blue-100 text-blue-600  ': toastType === 'info',
            'bg-yellow-100 text-yellow-600  ': toastType === 'warning'
          }"
        >
          <svg v-if="toastType === 'success'" class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
          </svg>
          <svg v-else-if="toastType === 'error'" class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
          </svg>
          <svg v-else-if="toastType === 'warning'" class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
          </svg>
          <svg v-else class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="flex-1">
          <p class="text-sm font-medium text-gray-900 ">
            {{ toastMessage }}
          </p>
        </div>
        <button 
          @click="showToast = false"
          class="flex-shrink-0 text-gray-400 hover:text-gray-600 "
        >
          <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { useAgentsStore } from '../stores/agents'

  const router = useRouter()
  const agentsStore = useAgentsStore()

  // State
  const isSubmitting = ref(false)
  const showProjectTypeDropdown = ref(false)
  const showToast = ref(false)
  const toastMessage = ref('')
  const toastType = ref('info')

  // Project Type Options
  const projectTypeOptions = [
    { value: 'ecommerce', label: 'E-commerce' },
    { value: 'toy', label: 'Toy & Collectibles' },
    { value: 'video', label: 'Video Production' },
    { value: 'content', label: 'Content Creation' },
    { value: 'marketing', label: 'Digital Marketing' },
    { value: 'education', label: 'Education' },
    { value: 'healthcare', label: 'Healthcare' },
    { value: 'finance', label: 'Finance' },
    { value: 'other', label: 'Other' }
  ]

  const form = reactive({
    name: '',
    projectType: '',
    customProjectType: '',
    description: '',
    projectRequirements: '',
    selectedAgents: [] as string[],
    apiConfig: {
      type: 'official',
      baseUrl: '',
      apiKey: '',
      modelName: ''
    }
  })

  // Computed
  const availableAgents = computed(() => agentsStore.agents)

  // Methods
  const formatCategory = (category: string) => {
    return category.split('-').map(word =>
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ')
  }

  const toggleProjectTypeDropdown = () => {
    showProjectTypeDropdown.value = !showProjectTypeDropdown.value
  }

  const selectProjectType = (value: string) => {
    form.projectType = value
    // Clear custom project type when selecting a predefined type
    if (value !== 'other') {
      form.customProjectType = ''
    }
    showProjectTypeDropdown.value = false
  }

  const getProjectTypeLabel = (value: string) => {
    if (value === 'other' && form.customProjectType) {
      return form.customProjectType
    }
    const type = projectTypeOptions.find(t => t.value === value)
    return type ? type.label : ''
  }

  // Toast methods
  const showToastMessage = (message: string, type: 'success' | 'error' | 'info' | 'warning' = 'info') => {
    toastMessage.value = message
    toastType.value = type
    showToast.value = true

    setTimeout(() => {
      showToast.value = false
    }, 3000)
  }

  const toggleAgentSelection = (agentId: string) => {
    const index = form.selectedAgents.indexOf(agentId)
    if (index > -1) {
      form.selectedAgents.splice(index, 1)
    } else {
      form.selectedAgents.push(agentId)
    }
  }

  const getRecommendedAgents = async () => {
    if (!form.projectRequirements.trim()) {
      showToastMessage('Please describe your project requirements first to get recommendations.', 'warning')
      return
    }

    try {
      // TODO: Implement actual recommendation API call
      console.log('Getting recommendations for:', form.projectRequirements)

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000))

      // Show success message
      showToastMessage('Recommendations will be available soon! Please manually select agents for now.', 'info')
    } catch (error) {
      console.error('Error getting recommendations:', error)
      showToastMessage('Failed to get recommendations. Please try again.', 'error')
    }
  }

  const handleSubmit = async () => {
    isSubmitting.value = true
    try {
      // TODO: Implement actual API call
      console.log('Creating team:', form)

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000))

      // Redirect to dashboard
      router.push('/dashboard')
    } catch (error) {
      console.error('Error creating team:', error)
    } finally {
      isSubmitting.value = false
    }
  }

  // Navigation method
  const navigateToAgent = (agentId: string) => {
    router.push(`/agent/${agentId}`)
  }

  // Lifecycle
  onMounted(() => {
    agentsStore.fetchAgents()
  })
</script>

<style scoped>
  .line-clamp-1 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>